<template>
  <div class="safety-archives-container">
    <div class="safety-body">
      <div class="tree-report">
        <SelectBlock
          :allowClear="true"
          v-model="conditions.orgCode"
          @change="blockChange($event)"
        ></SelectBlock>
        <div class="tree">
          <a-empty v-if="treeData.length == 0" />
          <a-tree
            v-else
            blockNode
            show-icon
            v-model="checkedKeys"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :replaceFields="{
              children: 'child',
              title: 'name',
              key: 'code',
            }"
            @expand="onExpand"
            @select="onSelect"
          >
            <template slot="title" slot-scope="{ name }">
              <a-tooltip>
                <template slot="title">
                  {{ name }}
                </template>
                <span>{{ name }}</span>
              </a-tooltip>
            </template>
            <template slot="custom" slot-scope="{ child }">
              <img
                v-if="child"
                class="menu-icon"
                src="@/assets/images/folder.png"
              />
              <img v-else class="menu-icon" src="@/assets/images/file.png" />
            </template>
          </a-tree>
        </div>
      </div>
      <div class="table-report">
        <div class="table-data-container">
          <div class="zhgd-data-report-header" header="WBS管理">
            <div>
              <a-button type="primary" @click="add()" v-if="powerButton">
                新增
              </a-button>
              <a-button @click="downloadTemplate" class="solid-line">
                下载模板
              </a-button>
              <a-button
                @click="importTemplate"
                :loading="importLoading"
                v-if="powerButton"
                class="solid-line"
              >
                批量导入
              </a-button>
              <input
                accept=".xls,.xlsx"
                @change="importExcel"
                type="file"
                ref="upload"
                id="upload"
                style="display: none"
              />
              <a-button @click="exportExcel" class="solid-line">
                导出
              </a-button>
            </div>
          </div>
          <div class="data-report-body">
            <div class="body-table" v-loading="loading">
              <vxe-table
                align="center"
                height="99%"
                :data="tableData"
                :column-config="{ resizable: true }"
                class="scrollbarStyle"
              >
                <vxe-column type="seq" title="序号" width="80"></vxe-column>
                <vxe-column
                  :title="item.title"
                  :field="item.key"
                  :key="index"
                  min-width="120"
                  show-overflow
                  v-for="(item, index) in columns"
                ></vxe-column>
                <vxe-column title="操作" fixed="right" width="240">
                  <template slot-scope="scope">
                    <div class="text-button-group">
                      <a-button
                        type="text"
                        @click="goDetail(scope.row, '1')"
                        v-if="powerButton"
                      >
                        查看
                      </a-button>
                      <a-button
                        type="text"
                        @click="goDetail(scope.row, '2')"
                        v-if="powerButton"
                      >
                        编辑
                      </a-button>
                      <a-button
                        type="text"
                        @click="handleDelClick(scope.row)"
                        class="del"
                        v-if="powerButton"
                      >
                        删除
                      </a-button>
                    </div>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
            <div>
              <vxe-pager
                background
                :current-page="pager.page"
                :page-size="pager.pageSize"
                :total="pager.total"
                :layouts="[
                  'PrevPage',
                  'JumpNumber',
                  'NextPage',
                  'Sizes',
                  'FullJump',
                ]"
                @page-change="paginationChange"
              >
                <template #left>
                  <div class="vxe-pager-left-tip-container">
                    第<span>1</span>到<span
                      >{{ Math.ceil(pager.total / pager.pageSize) }} 页</span
                    >共 <span> {{ pager.total }}</span
                    >条记录
                  </div>
                </template>
              </vxe-pager>
            </div>
          </div>
        </div>
      </div>
    </div>
    <wbs-model :visible.sync="visible" :model="model"></wbs-model>
  </div>
</template>
<script>
import SelectBlock from "@/components/wisdom-beam/SelectBlock";
import WbsModel from "./components/wbsModel.vue";
import {
  notificationTip,
  addAttributeByKey,
  downLoadFileByArraybuffer,
  getNowDateStr,
} from "@/utils";
import {
  getScheduleWbs,
  getWbsDelete,
  getWbsList,
  batchImport,
  downloadWbsTemplate,
  exportWbsExcel,
  getWbsOperateQx,
} from "@/api/wisdom-beam/quality-app";
export default {
  components: {
    SelectBlock,
    WbsModel,
  },
  data() {
    return {
      conditions: {
        //标段
        orgCode: undefined,
      },
      powerButton: false,
      importLoading: false,
      loading: false,
      columns: [
        {
          title: "单位工程",
          key: "unitWorks",
        },
        {
          title: "分部工程",
          key: "divisionalWorks",
        },
        {
          title: "子分部工程",
          key: "subDivisionalWorks",
        },
        {
          title: "分项工程",
          key: "itemWorks",
        },
        {
          title: "子分项工程",
          key: "subItemWorks",
        },
        {
          title: "工序",
          key: "procedureItem",
        },
        {
          title: "编号",
          key: "code",
        },
      ],
      tableData: [],
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      //弹框
      visible: false,
      model: {
        id: "",
        title: "",
        disable: false,
      },
    };
  },
  mounted() {},
  methods: {
    //监听标段切换
    blockChange() {
      this.getWbsOperateQxData();
      this.getTreeData();
      this.getTableData();
    },
    //查询按钮权限
    getWbsOperateQxData() {
      let { orgCode } = this.conditions;
      getWbsOperateQx(orgCode?.key || "")
        .then((res) => {
          this.powerButton = res.data.result;
        })
        .catch((_) => {
          this.powerButton = false;
        });
    },

    //获取树形结构
    getTreeData() {
      let { orgCode } = this.conditions;
      getScheduleWbs(orgCode?.key || "")
        .then((res) => {
          //初始化加载
          let tree = res?.data?.result || [];
          let filterData = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            tree,
            "child"
          );
          this.treeData = filterData;
        })
        .catch((_) => {
          this.treeData = [];
        });
    },

    //如果disabled == null 默认改成 0
    dealTree(data) {
      let res = [];
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if (item.disabled == null) {
          item.disabled = 0;
        }
        res.push(item);
        if (item.childList && item.childList.length > 0) {
          this.dealTree(item.childList);
        }
      }
      return res;
    },
    //树 展开 关闭
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //树选择事件
    onSelect(selectedKeys, e) {
      this.selectedKeys = selectedKeys;
      this.getTableData();
    },
    //监听分页
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
    //获取表格数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { orgCode } = this.conditions;
      getWbsList({
        orgCode: orgCode?.key || "",
        code: this.selectedKeys[0] ? this.selectedKeys[0] : "",
        page,
        pageSize,
      })
        .then((res) => {
          this.tableData = res.data.result.rows;
          this.pager.total = res.data.result.total;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.loading = false;
        });
    },
    //删除
    handleDelClick(row) {
      let that = this;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定删除所选内容?",
        content: "删除内容后,将无法恢复。",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          getWbsDelete(row.id)
            .then((res) => {
              notificationTip("success", "删除成功!");
              that.getTreeData();
              that.getTableData();
            })
            .catch();
        },
        onCancel() {},
      });
    },
    //下载模板
    downloadTemplate() {
      downloadWbsTemplate()
        .then((data) => {
          downLoadFileByArraybuffer(data, "WBS管理模板" + getNowDateStr());
        })
        .catch();
    },
    //导入
    importTemplate() {
      this.$refs.upload.click();
    },
    importExcel(event) {
      this.importLoading = true;
      let files = event.target.files;
      let formdata = new FormData();
      for (let i = 0; i < files.length; i++) {
        formdata.append("uploadFile", files[i]);
      }
      let { orgCode } = this.conditions;
      batchImport(formdata, orgCode?.key)
        .then((res) => {
          event.target.value = "";
          this.importLoading = false;
          let { data } = res;
          let errorMsg = data.result.errorMsg || [];
          if (errorMsg.length != 0) {
            let msg = errorMsg.join("");
            notificationTip("error", msg || "请检查必填项是否填写完整!");
          } else {
            notificationTip("success", "WBS管理导入成功");
          }
          this.getTreeData();
          this.getTableData();
        })
        .catch((err) => {
          event.target.value = "";
          this.importLoading = false;
        });
    },
    //导出
    exportExcel() {
      let { orgCode } = this.conditions;
      exportWbsExcel(orgCode.key)
        .then((data) => {
          downLoadFileByArraybuffer(data, "WBS管理" + getNowDateStr());
        })
        .catch((_) => {});
    },
    //新增
    add() {
      let { orgCode } = this.conditions;
      this.model = {
        id: "",
        title: "新增",
        disable: false,
        orgCode: orgCode.key,
        orgName: orgCode.label,
      };
      this.visible = true;
    },
    goDetail(record, i) {
      switch (i) {
        case "1":
          this.model = {
            id: record.id,
            title: "详情",
            disable: true,
            orgCode: record.orgCode,
            orgName: record.orgName,
          };
          this.visible = true;
          break;
        case "2":
          this.model = {
            id: record.id,
            title: "编辑",
            disable: false,
            orgCode: record.orgCode,
            orgName: record.orgName,
          };
          this.visible = true;
          break;
        default:
          break;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.safety-archives-container {
  box-sizing: border-box;
  padding: 0 0 10px 10px;
  height: 100%;
  .flex();
  flex-direction: column;
  .safety-body {
    flex: 1;
    background: #fff;
    overflow: hidden;
    margin: 10px 10px 0 0;
    .flex();
    .tree-report {
      width: 304px;
      height: 100%;
      .flex();
      flex-direction: column;
      /deep/.ant-select-selection {
        margin: 16px;
      }
      .tree {
        flex: 1;
        .custom-scrollbar();
        overflow-x: hidden !important;
      }
    }
    .table-report {
      flex: 1;
      .custom-scrollbar();
      overflow-y: hidden !important;
      .flex();
      flex-direction: column;
      border-left: 2px solid #eff1f6;
      .table-data-container {
        flex: 1;
        .flex();
        flex-direction: column;
        .zhgd-data-report-header {
          padding: 20px 20px;
          background-color: #fff;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          &::before {
            content: attr(header);
            height: 18px;
            border-left: 3px solid var(--primary-color);
            padding-left: 10px;
            font-size: 18px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #525a5d;
            line-height: 18px;
          }
        }
        .data-report-body {
          flex: 1;
          .flex();
          flex-direction: column;
          .body-table {
            flex: 1;
          }
          //按钮
          /deep/ .vxe-table {
            .ant-btn {
              margin: 0 15px;
              color: var(--primary-color);
              position: relative;
              &::after {
                position: absolute;
                content: "";
                height: 14px;
                width: 1px;
                background: #dcdee2;
                right: -15px;
                top: 50%;
                transform: translateY(-50%);
              }
              &.del {
                color: var(--echart-pale-red);
              }
              &:last-child {
                &::after {
                  display: none;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
